
#include "stdio.h"
#include <stdint.h>
#include "../section_locate.h"
#include "pt-thread.h"
#include "my_utils.h"
#include <math.h>
#include "algorithm_collector.h"


static void ks_bsearch_test(void);
PLACE_FUNC_AT_SEC(ks_bsearch_test);

static const float ir[] = {7.00, 8.00, 9.00, 10.00, 11.00, 12.00, 13.00, 14.01, 15.00, 16.00, 17.00, 18.01, 19.00, 20.00, 21.00, 21.99, 22.99, 24.02, 25.01, 26.00, 26.99, 28.03, 29.00, 30.02, 31.01, 31.98, 32.98, 34.04, 35.05, 36.01, 37.02, 37.96, 39.04, 40.05, 40.99, 41.97, 42.97, 44.01, 44.96, 46.06, 47.07, 47.98, 49.05, 50.01, 50.99, 52.01, 53.05, 53.97, 55.06, 56.03, 57.02, 58.04, 59.09, 59.98, 61.08, 62.03, 62.99, 63.98, 65.00, 66.04, 66.90, 68.00, 68.90, 70.06, 71.01, 71.99, 73.00, 74.03, 75.10, 75.92, 77.04, 77.91, 79.09, 80.01, 80.95, 81.92, 82.92, 83.94, 85.00, 86.09, 87.21, 87.98, 89.17, 89.99, 90.82, 92.12, 93.01, 93.93, 94.87, 95.83, 96.83, 97.86, 98.91, 100.01, 101.14, 101.72, 102.91, 104.14, 104.78, 106.09};


int fcmp(const void *key, const void *elt)
{
    float target = *(float *)key;
    float current = *(float *)elt;

    if (target < current){
        return -1;
    }else if(target >= current){
        return 1;
    }

    return 0;

}

int fcmp_last2(const void *key, const void *s, const void *e)
{
    float target = *(float *)key;
    float start = *(float *)s;
    float end = *(float *)e;


    if (fabs(target - start) < fabs(target - end)){
        return -1;
    }else{
        return 1;
    }

}

static int icmp(const void *key, const void *elt)
{
    int target = *(int *)key;
    int current = *(int *)elt;

    if (target < current){
        return -1;
    }else if(target > current){
        return 1;
    }else{
        return 0;
    }

}

static int icmp_last2(const void *key, const void *s, const void *e)
{
    int target = *(int *)key;
    int start = *(int *)s;
    int end = *(int *)e;


    if (target == start){
        return -1;
    }else if(target == end){
        return 1;
    }else{
        return 0;
    }

}

static void ks_bsearch_test(void)
{
    float *item;
    float key = 0;
    for(int i = 0; i < sizeof(ir) / sizeof(ir[0]); i++){
        key = (float)i + ir[0] + 0.5;
        item = ks_bsearch(&key, ir, sizeof(ir) / sizeof(ir[0]), sizeof (int), fcmp, fcmp_last2);
        if( item != NULL ){
            printf("key = %f, Found item = %f\n", key, *item);
        }else{
            printf("not Found\n");
        }

    }

    int data[] = {1, 2, 3, 4, 6, 8, 10, 11, 15, 19, 22, 32, 44, 46, 78, 99};
    int *found;
    int target = 19;
    found = ks_bsearch(&target, data, sizeof(data) / sizeof(data[0]), sizeof (int), icmp, icmp_last2);

    if( found != NULL ){
        printf("Found found = %d\n", *found);
    }else{
        printf("not Found\n");
    }

}
